package in.co.codedoc.processor;

import in.co.codedoc.ioc.Startable;
import in.co.codedoc.ioc.Stoppable;

public class ThreadedProcessor
	implements Startable,Stoppable,Runnable
{

	@Override
	public void Start()
	{
		if(!IsEnabled() || (GetWaitBetweenRuns() <= 0))
		{
			Logger.logger.info("Not starting processor thread " + getClass() + ". Disabled.");
			shutdown = true;
		}
		else	
		{
			Logger.logger.info("Starting " + getClass());
			shutdown = false;
			thread = new Thread(this);
			thread.setName(getClass().getSimpleName());
			thread.start();
		}
	}

	@Override
	public void Stop()
	{
		Logger.logger.info("Stopping " + getClass());
		shutdown = true;
		if(thread != null)
		{
			thread.interrupt();
			thread = null;
		}		
	}
	
	public void run()
	{
		long iteration = 0;
		while(!shutdown)
		{
			try
			{
				ProcessOnce(iteration++);
			}
			catch(Throwable th)
			{
				Logger.logger.error
				(
					"Exception while invoking ProcessOnce(iteration:" + 
					iteration + ")(IGNORED):" + th.getMessage(),
					th
				);
			}

			try
			{
				Thread.sleep(GetWaitBetweenRuns());
			}
			catch(Throwable th)
			{
				Logger.logger.debug("Exception while waiting between runs:" + th.getMessage(),th);
			}
		}
		
	}
	
	public void ProcessOnce(long iteration)
	{
		
	}
	
	public short GetWaitBetweenRuns()
	{
		return (short)60000;
	}
	
	public boolean IsEnabled()
	{
		return true;
	}
	
	private boolean shutdown;
	private Thread thread;
}
